package com.chinaoly.sdk.http;

import com.chinaoly.sdk.util.LogUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;


import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

import static okhttp3.internal.http.HttpHeaders.hasBody;

public final class MyInterceptor implements Interceptor {

    private final Charset UTF8 = Charset.forName("UTF-8");


    @Override
    public Response intercept(Chain chain) throws IOException {
        long startNs = System.nanoTime();
        int timeOut = 15;
        LogUtils.e("timeOut:" + timeOut);
        final Request request = chain.request();
        Buffer requestBuffer = new Buffer();
        if (request.body() != null) {
            request.body().writeTo(requestBuffer);
            LogUtils.e("jcsuc:request.body() = ", requestBuffer.toString());
        } else {
            LogUtils.e("jcsuc ", "request.body() == null");
        }
        //打印url信息
        final Response response = chain.proceed(request);
        response.body();
        LogUtils.e("response = ", response.toString());

        ResponseBody responseBody = response.body();

        String rBody = null;
        if (hasBody(response)) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }
            rBody = buffer.clone().readString(charset);

        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        LogUtils.e("tookMs=" + tookMs + "; responseBody:", rBody);
        return response;
    }

}